package javaroke.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javaroke.excepcion.LoginExcepcion;

import javaroke.excepcion.DAOExcepcion;
import javaroke.modelo.Persona;
import javaroke.util.ConexionBD;

public class PersonaDAO extends BaseDAO{
	
	public Persona insertar(Persona vo) throws DAOExcepcion {
		String query = "insert into Persona (dni,nombres , paterno, materno) values (?,?,?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);

			stmt.setInt(1, vo.getDni());
			stmt.setString(2, vo.getNombres());
			stmt.setString(3, vo.getPaterno());
			stmt.setString(4, vo.getMaterno());


			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar la Reserva");
			}
			// Obtener el ultimo id
			int id = 0;
			query = "select last_insert_id()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt(1);
			}
			vo.setDni(id);

		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}

	public Persona validar(String dni)
			throws DAOExcepcion, LoginExcepcion {
		String query = "select dni, nombres, paterno,"
				+ "materno "
				+ "from persona where dni=? ";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		Persona vo = new Persona();
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, dni);
			rs = stmt.executeQuery();

			if (rs.next()) {
				vo.setDni(Integer.parseInt(rs.getString("dni")));
				vo.setNombres(rs.getString("nombres"));
				vo.setPaterno(rs.getString("paterno"));
				vo.setMaterno(rs.getString("materno"));
			} else {
				throw new LoginExcepcion("No existe");
			}
		} catch (LoginExcepcion e) {
			System.err.println(e.getMessage());
			throw new LoginExcepcion(e.getMessage());
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}	
	
	
}
